using System;
using System.ServiceModel;

namespace Destra.Common.Services
{
    public class ClientScope<TChannel> : IDisposable
        where TChannel : class
    {
        private ClientBase<TChannel> m_client;

        public ClientScope(ClientBase<TChannel> client)
        {
            m_client = client;
        }

        public ClientBase<TChannel> Channel
        {
            get
            {
                return m_client;
            }
        }

        public TChannel Client
        {
            get
            {
                return (m_client as TChannel);
            }
        }

        // IDisposable
        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (m_client != null)
            {
                if (m_client.State != CommunicationState.Closed)
                {
                    try
                    {
                        m_client.Close();
                    }
                    catch
                    {
                        m_client.Abort();
                    }
                }
            }
        }
    }
}